<?php
namespace app\api\controller;

use app\api\model\wxapp\Setting as WxappSettingModel;
use app\common\enum\ding\Ribao as SceneEnum;
use app\common\model\ding\Ribao as RibaoModel;
use app\common\service\message\ding\Birthday as BirthdayService;
use app\common\service\message\ding\Yeji as YejiService;
use app\store\service\wxapp\Message as MessageService;
use app\store\service\wxapp\User as WxUser;
use think\facade\Db;

/**
 * 默认控制器
 * Class Index
 * @package app\api\controller
 */
class Index
{
    public function index()
    {
        //更新员工公众号openid
        // $clerks = Db::name('store_shop_clerk')->select()->toArray();
      
        // foreach ($clerks as $key => $value) {
        //     $unionid = Db::name('user_oauth')->where('user_id', $value['user_id'])->value('unionid');
        //     $openid  = Db::name('user_oauth_wxapp')->where('unionid', $unionid)->value('open_id');
        //     if ($openid) {

        //         Db::name('store_shop_clerk')->where('clerk_id', $value['clerk_id'])->update(['oauth_id' => $openid]);
        //     }
        // }
        // echo '成功';
        //echo '当前访问的index.php，请将index.html设为默认站点入口';

        $members = Db::name('ding_clerk_member')->select()->toArray();

        foreach ($members as $key => $value) {
            $dd = Db::name('ding_clerk_member')->where('mobile', $value['mobile'])->where('shop_id', $value['shop_id'])
                ->where('clerk_id', 0)->find();
            if ($dd) {

            } else {
                $data['clerk_id']    = 0;
                $data['shop_id']     = $value['shop_id'];
                $data['real_name']   = $value['real_name'];
                $data['times']       = $value['times'];
                $data['mobile']      = $value['mobile'];
                $data['store_id']    = $value['store_id'];
                $data['create_time'] = $value['create_time'];
                $data['status']      = $value['status'];
                $data['user_id']     = $value['user_id'];
                $data['month']       = $value['month'];
                $data['day']         = $value['day'];
                $data['type']        = $value['type'];
                $data['remark']      = $value['remark'];
                $data['last_time']   = $value['last_time'];
                $data['remark']      = $value['remark'];
                $data['role']        = $value['role'];
                $data['sex']         = $value['sex'];
                Db::name('ding_clerk_member')->insert($data);
            }
        }

        // 获取当前小程序信息
        //$config = self::getMpWxConfig();
        // 微信登录 (获取session_key)
        // $WxUser = new Link($config['app_id'], $config['app_secret']);
        // $param['path'] = 'pagesNew/index/index';

        // $result = $WxUser->getLink($param);
        // $url = $result['url_link'];

        //echo $url;

    }
    //计算每日日报数据
    public function ribaoshuju()
    {
        $shops = Db::name('store_shop')->where('is_delete', 0)
            ->where('status', 1)->field('shop_id')->select()->toArray();



        $time = time() - 86400;
            $date = Date('Y-m-d', $time);

        foreach ($shops as $key => $value) {

            $shopId  = $value['shop_id'];
            $where   = [];
            $where[] = ['shop_id', '=', $shopId];
            $ribao   = [];
            //多挣
            $count = Db::name('ding_order')->where('date', $date)
                ->where('shop_id', $shopId)->where('status', '<>', 30)->count();
            $ribao['shop_id']  = $value['shop_id'];
            $ribao['clerk_id'] = 0;
            $ribao['value']    = $count * 500;
            $ribao['date']     = $date;

            if ($count > 0) {
                RibaoModel::add(SceneEnum::DZ, $ribao, '订单数：' . $count);
            }

            //节省
            //使用点菜功能
            $orders = Db::name('ding_order')->field('id')
                ->where('shop_id', $shopId)->where('date', $date)->select()->toArray();

            $order_total = count($orders);
            $ids         = array_column($orders, 'id');
            $countMenu   = Db::name('ding_order_menu')->where('order_id', 'in', $ids)->group('order_id')->count();
            $ribao       = [];
            //店铺分享
            $countMake         = Db::name('store_shop_make_log')->where('create_time', '>', strtotime($date))->where('shop_id', $shopId)->where('type', 1)->count();
            $ribao['shop_id']  = $value['shop_id'];
            $ribao['clerk_id'] = 0;
            $ribao['value']    = $countMake * 3 + $countMenu * 20;
            $ribao['date']     = $date;
            if ($ribao['value'] > 0) {
                RibaoModel::add(SceneEnum::JS, $ribao, '');
            }

            //损失

            $sunshiCount       = $order_total - $countMenu;
            $ribao             = [];
            $ribao['shop_id']  = $value['shop_id'];
            $ribao['clerk_id'] = 0;
            $ribao['value']    = $sunshiCount * 20;
            $ribao['date']     = $date;
            if ($sunshiCount > 0) {
                RibaoModel::add(SceneEnum::SS, $ribao, '订单数：' . $sunshiCount);
            }

            //门店曝光量
            $shop_views       = Db::name('store_shop_view')->where($where)->count();
            $shop_share_views = Db::name('store_shop_make_log')->where($where)->count();

            //门店曝光
            $shop_views        = $shop_views + $shop_share_views;
            $ribao             = [];
            $ribao['shop_id']  = $value['shop_id'];
            $ribao['clerk_id'] = 0;
            $ribao['value']    = $shop_views;
            $ribao['date']     = $date;

            if ($shop_views > 0) {
                RibaoModel::add(SceneEnum::MDBGL, $ribao, '');
            }

            //有效订单
            $yxdd_order = Db::name('ding_order')->where('date', $date)
                ->where('shop_id', $shopId)->where('status', '<>', 30)->count();
            $ribao             = [];
            $ribao['shop_id']  = $value['shop_id'];
            $ribao['clerk_id'] = 0;
            $ribao['value']    = $yxdd_order;
            $ribao['date']     = $date;
            if ($shop_views > 0) {
                RibaoModel::add(SceneEnum::YXDD, $ribao, '');
            }
            //取消订单
            $qxdd_order = Db::name('ding_order')->where('date', $date)
                ->where('shop_id', $shopId)->where('status', '=', 30)->count();
            $ribao             = [];
            $ribao['shop_id']  = $value['shop_id'];
            $ribao['clerk_id'] = 0;
            $ribao['value']    = $qxdd_order;
            $ribao['date']     = $date;
            if ($shop_views > 0) {
                RibaoModel::add(SceneEnum::QXDD, $ribao, '');
            }
            //裂变用户数

            $ribao             = [];
            $ribao['shop_id']  = $value['shop_id'];
            $ribao['clerk_id'] = 0;
            $ribao['value']    = Db::name('ding_shop_liebian')->where($where)->count();
            $ribao['date']     = $date;
            if ($shop_views > 0) {
                RibaoModel::add(SceneEnum::LBYHS, $ribao, '');
            }
            //邀请函曝光量
            $ribao             = [];
            $ribao['shop_id']  = $value['shop_id'];
            $ribao['clerk_id'] = 0;
            $ribao['value']    = Db::name('ding_order_view')->where($where)->count();
            $ribao['date']     = $date;
            if ($shop_views > 0) {
                RibaoModel::add(SceneEnum::YQHBGL, $ribao, '');
            }
            //邀请函裂变量
            $ribao             = [];
            $ribao['shop_id']  = $value['shop_id'];
            $ribao['clerk_id'] = 0;
            $ribao['value']    = Db::name('ding_shop_liebian')->where($where)->where('status', 1)->count();
            $ribao['date']     = $date;
            if ($shop_views > 0) {
                RibaoModel::add(SceneEnum::YQHLBL, $ribao, '');
            }

        }

        $clerks = Db::name('store_shop_clerk')->where('is_delete', 0)
            ->where('status', 1)->field('shop_id,clerk_id')->select()->toArray();

        foreach ($clerks as $key => $value) {

            $shopId  = $value['shop_id'];
            $clerkId = $value['clerk_id'];

            $where   = [];
            $where[] = ['clerk_id', '=', $clerkId];
            $ribao   = [];
            //多挣
            $count             = Db::name('ding_order')->where('date', $date)->where('clerk_id', $clerkId)->where('status', '<>', 30)->count();
            $ribao['shop_id']  = $value['shop_id'];
            $ribao['clerk_id'] = $value['clerk_id'];
            $ribao['value']    = $count * 500;
            $ribao['date']     = $date;
            if ($count > 0) {
                RibaoModel::add(SceneEnum::DZ, $ribao, '订单数：' . $count);
            }

            //节省
            //使用点菜功能
            $orders = Db::name('ding_order')->field('id')
                ->where('clerk_id', $clerkId)->where('date', $date)->select()->toArray();

            $order_total = count($orders);
            $ids         = array_column($orders, 'id');
            $countMenu   = Db::name('ding_order_menu')->where('order_id', 'in', $ids)->group('order_id')->count();
            $ribao       = [];
            //店铺分享
            $countMake = Db::name('store_shop_make_log')
                ->where('create_time', '>', strtotime($date))->where('type', 1)->where('clerk_id', $clerkId)->count();
            $ribao['shop_id']  = $value['shop_id'];
            $ribao['clerk_id'] = $value['clerk_id'];
            $ribao['date']     = $date;
            $ribao['value']    = $countMake * 3 + $countMenu * 20;
            if ($ribao['value'] > 0) {
                RibaoModel::add(SceneEnum::JS, $ribao, '');
            }
            //损失

            $sunshiCount       = $order_total - $countMenu;
            $ribao             = [];
            $ribao['shop_id']  = $value['shop_id'];
            $ribao['clerk_id'] = $value['clerk_id'];
            $ribao['value']    = $sunshiCount * 20;
            $ribao['date']     = $date;
            if ($sunshiCount > 0) {
                RibaoModel::add(SceneEnum::SS, $ribao, '订单数：' . $sunshiCount);
            }

            //门店曝光量
            $shop_views       = Db::name('store_shop_view')->where($where)->count();
            $shop_share_views = Db::name('store_shop_make_log')->where($where)->count();

            //门店曝光
            $shop_views        = $shop_views + $shop_share_views;
            $ribao             = [];
            $ribao['shop_id']  = $value['shop_id'];
            $ribao['clerk_id'] = $clerkId;
            $ribao['value']    = $shop_views;
            $ribao['date']     = $date;
            if ($shop_views > 0) {
                RibaoModel::add(SceneEnum::MDBGL, $ribao, '');
            }

            //有效订单
            $yxdd_order = Db::name('ding_order')->where('date', $date)
                ->where('shop_id', $shopId)->where('status', '<>', 30)->count();
            $ribao             = [];
            $ribao['shop_id']  = $value['shop_id'];
            $ribao['clerk_id'] = $clerkId;
            $ribao['value']    = $yxdd_order;
            $ribao['date']     = $date;
            if ($shop_views > 0) {
                RibaoModel::add(SceneEnum::YXDD, $ribao, '');
            }
            //取消订单
            $qxdd_order = Db::name('ding_order')->where('date', $date)
                ->where('shop_id', $shopId)->where('status', '=', 30)->count();
            $ribao             = [];
            $ribao['shop_id']  = $value['shop_id'];
            $ribao['clerk_id'] = $clerkId;
            $ribao['value']    = $qxdd_order;
            $ribao['date']     = $date;
            if ($shop_views > 0) {
                RibaoModel::add(SceneEnum::QXDD, $ribao, '');
            }
            //裂变用户数

            $ribao             = [];
            $ribao['shop_id']  = $value['shop_id'];
            $ribao['clerk_id'] = $clerkId;
            $ribao['value']    = Db::name('ding_shop_liebian')->where($where)->count();
            $ribao['date']     = $date;
            if ($shop_views > 0) {
                RibaoModel::add(SceneEnum::LBYHS, $ribao, '');
            }
            //邀请函曝光量
            $ribao             = [];
            $ribao['shop_id']  = $value['shop_id'];
            $ribao['clerk_id'] =$clerkId;
            $ribao['value']    = Db::name('ding_order_view')->where($where)->count();
            $ribao['date']     = $date;
            if ($shop_views > 0) {
                RibaoModel::add(SceneEnum::YQHBGL, $ribao, '');
            }
            //邀请函裂变量
            $ribao             = [];
            $ribao['shop_id']  = $value['shop_id'];
            $ribao['clerk_id'] = $clerkId;
            $ribao['value']    = Db::name('ding_shop_liebian')->where($where)->where('status', 1)->count();
            $ribao['date']     = $date;
            if ($shop_views > 0) {
                RibaoModel::add(SceneEnum::YQHLBL, $ribao, '');
            }
        }
  
        echo '计算完成';
    }
    //每日报表-公众号。发送给老板
    public function sendBaobiao()
    {
        $messageService = new YejiService(10001);

        $shops = Db::name('store_shop_clerk')->alias('c')
            ->join('user_oauth u', 'u.user_id=c.user_id')
            ->join('user_oauth_wxapp w', 'w.unionid=u.unionid')
            ->where('c.role_id', '=', 3)
            ->where('c.is_delete', 0)
            ->where('c.status', 1)
            ->field('w.open_id')
            ->select()->toArray();
        //暂停
        exit;
//exit;
        foreach ($shops as $key => $value) {
            // 执行发送

            $MessageService         = new MessageService;
            $content['template_id'] = 'f_-0dcAA9sSC4KM1JzMgwgoyaljyxe3yrnig7wN8sNQ';
            $content['page']        = 'pagesNew/help/add?id=' . $data['order_id'];

            $content['data']['time4'] = Date('Y-m-d H:i');
            //$content['data']['phrase9'] = $data['real_name'];
            $content['data']['phone_number14'] = $data['mobile'];
            $content['data']['time16']         = $data['date'] . ' ' . $data['time'];
            $content['data']['thing3']         = '订厢';

            //暂时注释
            $MessageService->send($opend_id, $content);

        }
        echo '公众号报表发送完成';
    }
    //业绩发送短信
    public function sendYeji()
    {
        $messageService = new YejiService(10001);
        $shops          = Db::name('store_shop')->where('balance', '>', 0)->select()->toArray();
        $end            = strtotime(Date('Y-m-d'));
        $start          = $end - 86400;

        foreach ($shops as $key => $value) {
            $order_total = Db::name('ding_order')
                ->where('status', '<>', 30)
                ->where('shop_id', $value['shop_id'])->where('create_time', '>=', $start)->where('create_time', '<', $end)->count();
            $baoguang_total = Db::name('ding_shop_visit')

                ->where('shop_id', $value['shop_id'])->where('create_time', '>=', $start)
                ->where('create_time', '<', $end)->count();
            $liebian_total = Db::name('ding_clerk_member')
                ->where('shop_id', $value['shop_id'])
                ->where('create_time', '>=', $start)
                ->where('create_time', '<', $end)->count();
            $value['order_total']    = $order_total;
            $value['baoguang_total'] = $baoguang_total;
            $value['liebian_total']  = $liebian_total;
            $users                   = Db::name('store_shop_clerk')
                ->where('shop_id', $value['shop_id'])
                ->where('role_id', 3)
                ->where('data_msg', 1)
                ->select()->toArray();

            if (! empty($users)) {
                $send['users'] = $users;
                $send['shop']  = $value;
                $messageService->send($send);

            }

        }
        echo '短信发送完成';
    }
    //生日祝福短信
    public function sendBirthday()
    {
        $messageService = new BirthdayService(10001);
        $shops          = Db::name('store_shop')->where('birthday_msg', 1)->where('balance', '>', 0)->select()->toArray();

        //当前时间，3天后
        $time = time() + 86400 * 3;

        $month = Date('m月', $time);
        $day   = Date('d日', $time);
        foreach ($shops as $key => $value) {
            $users = Db::name('ding_clerk_member')->alias('m')
                ->join('user u', 'u.mobile=m.mobile')
                ->where('u.birthday', '>', 0)
                ->where('m.shop_id', $value['shop_id'])
                ->where('u.month', $month)
                ->where('u.day', $day)
                ->select()->toArray();

            if (! empty($users)) {
                $send['users'] = $users;
                $send['shop']  = $value;

                $messageService->send($send);

            }

        }

        //会员生日当天
        $time = time();

        $month = Date('m月', $time);
        $day   = Date('d日', $time);
        foreach ($shops as $key => $value) {
            $users = Db::name('ding_clerk_member')->alias('m')
                ->join('user u', 'u.mobile=m.mobile')
                ->where('u.birthday', '>', 0)
                ->where('m.shop_id', $value['shop_id'])
                ->where('u.month', $month)
                ->where('u.day', $day)
                ->select()->toArray();

            if (! empty($users)) {
                $send['users'] = $users;
                $send['shop']  = $value;

                $messageService->send($send);

            }

        }

        echo '短信发送完成';
    }
    private static function getMpWxConfig(): array
    {
        $wxConfig = WxappSettingModel::getWxappConfig();
        if (empty($wxConfig['app_id']) || empty($wxConfig['app_secret'])) {
            throwError('请到后台小程序设置填写AppID和AppSecret参数');
        }
        return $wxConfig;
    }
    public function getUser()
    {
        $next_openid = Db::name('wxapp_setting')->where('key', 'next_openid')->value('values');

        $WxUser = new WxUser;
        $result = $WxUser->getUser($next_openid);

        if (isset($result['data'])) {
            // if (! empty($result['data']['next_openid'])) {
            //     $this->getUser($result['data']['next_openid']);
            // }

            $list = $result['data']['openid'];
            foreach ($list as $value) {
                $dd = Db::name('user_oauth_wxapp')->where('open_id', $value)->find();
                if (! $dd) {
                    $user['open_id']     = $value;
                    $user['create_time'] = time();
                    $user['store_id']    = 10001;
                    $insertData[]        = $user;
                }

            }
            if (! empty($insertData)) {
                Db::name('user_oauth_wxapp')->insertAll($insertData);
            }

            if (isset($result['next_openid'])) {
                Db::name('wxapp_setting')->where('key', 'next_openid')->update(['values' => $result['next_openid']]);
            }

        }

        echo '成功';
    }
    public function updateUser()
    {

        $list   = Db::name('user_oauth_wxapp')->where('unionid', '')->limit(100)->order('id asc')->select()->toArray();
        $WxUser = new WxUser;
        foreach ($list as $value) {
            $result = $WxUser->getUnionid($value['open_id']);
            if ($result && isset($result['unionid'])) {
                Db::name('user_oauth_wxapp')->where('open_id', $value['open_id'])->update(['unionid' => $result['unionid']]);
            }

        }

        echo '成功';
    }
}
